package com.qen.socket.nio

import cn.hutool.core.io.BufferUtil
import cn.hutool.core.lang.Console
import cn.hutool.core.util.StrUtil
import cn.hutool.socket.nio.NioClient
import java.nio.ByteBuffer
import java.util.Scanner

fun main() {
    val client = NioClient("127.0.0.1", 8080)
    client.setChannelHandler { sc ->
        val readBuffer = ByteBuffer.allocate(1024)
        val readBytes = sc.read(readBuffer)
        if (readBytes > 0) {
            readBuffer.flip()
            val bytes = ByteArray(readBuffer.remaining())
            readBuffer.get(bytes)
            val body = StrUtil.utf8Str(bytes)
            Console.log("[${sc.remoteAddress}]:${body}")
        } else if (readBytes < 0) {
            sc.close()
        }
    }
    client.listen()
    client.write(BufferUtil.createUtf8("你好。\n"))
    client.write(BufferUtil.createUtf8("你好2。"))
    Console.log("请输入发送的消息：")
    val sca = Scanner(System.`in`)
    while (sca.hasNextLine()) {
        val req = sca.nextLine()
        if (req != null && req.trim().length > 0) {
            client.write(BufferUtil.createUtf8(req))
        }
    }
}